package edu.vt.ece4564.bluetendance.students;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import edu.vt.ece4564.bluetendance.database.DatabaseConnector;

public class BluetoothMappingGetter implements Runnable {
	private HttpServletResponse response;
	private int classID;

	public BluetoothMappingGetter(HttpServletResponse response, int classID) {
		this.response = response;
		this.classID = classID;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		DatabaseConnector dc = DatabaseConnector.get();
		
		dc.commandText = "call SP_GetBluetoothMapping('" + classID + "');";
		ResultSet classListingResults = dc.executeQuery();
		
		Map<String, String> map = new HashMap<String, String>();

		try {
			while (classListingResults.next()) {
				map.put(classListingResults.getString("BluetoothDeviceHardwareID"), classListingResults.getString("StudentName"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		response.setContentType("application/plain");

		PrintWriter out = null;
		
		try {
			out = response.getWriter();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		if (map.size() > 0) {
			JSONArray array = new JSONArray();
			JSONObject obj = new JSONObject();
			for (String key : map.keySet()) {
				obj.put(key, map.get(key));
			}
			array.add(obj);
			
			StringBuilder sb = new StringBuilder(array.toString());
			if (sb.charAt(0) == '[') {
				sb.deleteCharAt(0);
			}
			if (sb.charAt(sb.length() - 1) == ']') {
				sb.deleteCharAt(sb.length() - 1);
			}
			out.println(sb);
		}
		else {
			JSONObject obj=new JSONObject();

			obj.put("valid","false");
			out.println(obj.toString());
		}
		out.close();
	}
}
